package logic

import (
	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"
	"book-hub/cache"
	"book-hub/models"
	"book-hub/pkg"
	"context"
	"fmt"
	"math/rand"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *bookrpc.LoginRequest) (*bookrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(cache.Ctx, "sensms"+in.Mobile).Result()
	if result != in.SenSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user models.User
	models.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID != 0 {
		if user.Password != pkg.Md5str(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	} else {
		i := rand.Intn(9000) + 1000
		a := strconv.Itoa(i)
		user = models.User{
			Mobile:   in.Mobile,
			Password: pkg.Md5str(in.Password),
			Name:     "用户_" + a,
			Image:    "https://cn.bing.com/images/search?q=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&FORM=IQFRBA&id=88096C8C1D7696112C3B5C56EE8CE04A33FE26E2",
		}
		models.DB.Create(&user)
	}
	return &bookrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
